//
//  TimerHome.swift
//  CrseAsst
//
//  Created by 申铭 on 2024/2/22.
//

import SwiftUI
import CoreData

struct TimerHome: View {
    @Environment(\.managedObjectContext) private var viewContext
    @State private var showDeleteAlert: Bool = false
    
    @State private var deleteOffsets = IndexSet()
    
    @FetchRequest(sortDescriptors: [
        NSSortDescriptor(keyPath: \CATimer.createTime, ascending: false),
        NSSortDescriptor(keyPath: \CATimer.sort, ascending: false)]
                  , animation: .default)
    private var items: FetchedResults<CATimer>
    
    var body: some View {
        NavigationView {
            List {
                ForEach(items, id: \.uuid) { item in
                    NavigationLink(destination: TimingView(caTimer: item)) {
                        TimerCell(timer: item)
                    }
                }
                .onMove(perform: { indices, newOffset in
                    log.verbose("onMove:\(indices),\(newOffset)")
                })
                .onDelete(perform: deleteItems(offsets:))
                .hideListRowSeperator()
            }
            .listStyle(.plain)
            .toolbar {
                ToolbarItem {
                    NavigationLink(destination: EditTimerView()) {
                        Label("Add Item", systemImage: "plus")
                    }
                }
            }
            .alert(isPresented: $showDeleteAlert, content: {
                deleteAlert()
            })
            .navigationBarTitle("练习")
            .navigationBarTitleDisplayMode(.automatic)
        }
    }
    
    private func deleteItems(offsets: IndexSet) {
        log.verbose("deleteItems_offsets:\(offsets)")
        showDeleteAlert = true
        deleteOffsets = offsets
    }
    
    private func deleteAlert() -> Alert {
        let alert = Alert(title: Text("提示"), message: Text("是否确认删除"), primaryButton: .destructive(Text("删除"), action: {
            deleteItems2(offsets: deleteOffsets)
        }), secondaryButton: .cancel(Text("取消")))
        return alert
    }
    
    private func deleteItems2(offsets: IndexSet) {
        log.verbose("deleteItems_offsets:\(offsets)")
        
        withAnimation {
            offsets.map { items[$0] }.forEach(viewContext.delete)
            do {
                try viewContext.save()
            } catch {
                log.error(error)
            }
        }
    }
}

struct TimerCell: View {
    let timer: CATimer
    
    var body: some View {
        HStack(spacing: 12) {
            RoundedRectangle(cornerRadius: 6)
                .fill(getColor())
                .frame(width: 50, height: 50)
            VStack(alignment: .leading) {
                Text(timer.name ?? "")
                    .font(.title3)
                    .padding(EdgeInsets(top: 0, leading: 0, bottom: 3, trailing: 0))
                Text(getDetailContent())
                    .foregroundColor(.gray)
                    .font(Font.system(size: 13))
                    .padding(EdgeInsets(top: 0, leading: 0, bottom: 3, trailing: 0))
            }
            Spacer()
        }
        .foregroundColor(.primary)
    }
    
    private func getColor() -> Color {
        guard let hex = timer.color else {
            return .clear
        }
        
        return Color(hex: hex) ?? .clear
    }
    
    private func getDetailContent() -> String {
        var typeName = ""
        
        if timer.type == TimerType.timer.id {
            typeName = "纯计时"
        } else if timer.type == TimerType.scheduleTime.id {
            typeName = "时间段"
            let format = "HH:mm"
            let start = timer.startTime.formatTime(format)
            let end = timer.endTime.formatTime(format)
            typeName = "\(typeName) | \(start) ~ \(end)"
        } else if timer.type == TimerType.countDown.id {
            typeName = "倒计时"
            let s = timer.duration.formatHMS(sh: false, sm: true, ss: false)
            typeName = "\(typeName) | \(s)"
        }
        
        return typeName
    }
}

#Preview {
    TimerHome().environment(\.managedObjectContext, PersistenceController.shared.container.viewContext)
//    TimerCell()
}
